package ar.Location.Api.GooglePlace;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParserFactory;

import android.util.Log;
import android.util.Xml;
import ar.Location.Constant.Define;
import ar.Location.Helper.HttpProvider;
import ar.Location.PlaceApi.AbsAPI;
import ar.Location.PlaceObject.Place;

public class GooglePlaceAPI extends AbsAPI {

	private static final String TAG = "GooglePlaceAPI";

	@Override
	public ArrayList<Place> getListPlacesByGeoPoint(String latitude,
			String longitude, int radiusMetters) {
		// TODO Auto-generated method stub
		return getListPlacesByType(latitude, longitude, "", radiusMetters);
	}

	@Override
	public ArrayList<Place> getListPlacesByType(String latitude,
			String longitude, String type, int radiusMetters) {
		// TODO Auto-generated method stub
		try {
			if (radiusMetters < 100) {
				radiusMetters = 100;
			} else {
				if (radiusMetters > 50000) {
					radiusMetters = 50000;
				}
			}

			String url = Define.GOOGLE_API_SEARCH_REQUEST;
			url = url.replace("@location", latitude + "," + longitude);
			url = url.replace("@types", type);
			url = url.replace("@key", Define.GOOGLE_API_KEY);
			url = url.replace("@radius", String.valueOf(radiusMetters));
			url = url.replace("@sensor", "true");

			SAXParserFactory spf = SAXParserFactory.newInstance();
			spf.setValidating(false);
			InputStream inputStream = HttpProvider.getInputStream(url);
			GooglePlaceHandler googlePlaceHandler = new GooglePlaceHandler(type);
			Xml.parse(inputStream, Xml.Encoding.UTF_8, googlePlaceHandler);
			return googlePlaceHandler.getListResults();
		} catch (Exception e) {
			// TODO: handle exception
			Log.d(TAG, e.getMessage());
			return null;
		}
	}
}
